﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using NerdWare.Crm2011VsTools.Core.Crm;

namespace NerdWare.Crm2011VsTools.DataModel
{
    class CrmExplorerModel
    {
        [ImportMany(typeof(IDiscoverCrm))]
        public IEnumerable<Lazy<IDiscoverCrm, ICrmVersion>> CrmPlugins;

        public List<IDiscoverCrm> CrmServer = new List<IDiscoverCrm>();

        private CompositionContainer _crmPlugins;

        public CrmExplorerModel()
        {
            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName, "NerdWare.CrmPlugin.*.dll"));

            _crmPlugins = new CompositionContainer(catalog);

            _crmPlugins.ComposeParts(this);

            foreach (Lazy<IDiscoverCrm, ICrmVersion> crmPlugin in CrmPlugins)
            {
                CrmApplicationDescriptor crmApplicationDescriptor = new CrmApplicationDescriptor(crmPlugin.Metadata.CrmVersion, "crmdc1", 5555);
                crmPlugin.Value.SetApplicationDescriptor(crmApplicationDescriptor);

                CrmServer.Add(crmPlugin.Value);
            }
        }
    }
}
